#include "container/list.h"
#include <stdio.h>
#include <string.h>

void test_list(void)
{
    printf("\n----------test_list-------------\n");
	cotList_t listTable;
	
	cotList_Init(&listTable);

	cotList_PushBack(&listTable, "123", strlen("123") + 1);
    cotList_PushBack(&listTable, "1234", strlen("1234") + 1);
    cotList_PushFront(&listTable, "12345", strlen("12345") + 1);
    cotList_PushFront(&listTable, "123456", strlen("123456") + 1);
    cotList_PushFront(&listTable, "1234567", strlen("1234567") + 1);

    printf("list empty: %d, size: %d\n", cotList_Empty(&listTable), cotList_Size(&listTable));

    printf("add after:\n");
	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    printf("front item: [%d] %s\n", cotList_Front(&listTable)->length, (char *)cotList_Front(&listTable)->pData);
    printf("back item:  [%d] %s\n", cotList_Back(&listTable)->length, (char *)cotList_Back(&listTable)->pData);

    int cnt = 0;

	for_list(item, listTable)
    {
        cnt++;
        if (cnt == 2) // 循环内删除第2个元素
        {
            item = cotList_Erase(&listTable, item);
        }
        else
        {
            item = cotList_Next(item);
        }
    }

    printf("remove after:\n");
	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    cotList_PopFront(&listTable); // 弹出头元素

    printf("pop after:\n");
	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    cotList_Clear(&listTable); // 清除所有元素

    printf("clear after:\n");
	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    printf("\n");

    // 重新添加
	cotList_PushBack(&listTable, "123", strlen("123") + 1);
    cotList_PushBack(&listTable, "1234", strlen("1234") + 1);
    cotList_PushFront(&listTable, "12345", strlen("12345") + 1);
    cotList_PushFront(&listTable, "123456", strlen("123456") + 1);
    cotList_PushFront(&listTable, "1234567", strlen("1234567") + 1);

    printf("r add after:\n");

	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    cotList_t listTable2;

    cotList_Swap(&listTable, &listTable2); // 链表内存交换

    printf("sawp after:\n");
    printf("  listTable-1: \n");
	for_list_each(item, listTable)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    printf("  listTable-2: \n");
	for_list_each(item, listTable2)
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}

    printf("  listTable-2 r:\n");
	for_list_each_r(item, listTable2) // 反向迭代输出
	{
	    printf("    item: [%d] %s\n", item->length, (char *)item->pData);
	}
}

